<template>
  <a-select
    v-model:value="localValue"
    :placeholder="placeholder"
    :allowClear="allowClear"
    :disabled="disabled"
    :filterOption="false"
    showSearch
    @search="handleSearch"
    @change="handleChange"
    :style="style"
    @popupScroll="handlePopupScroll"
  >
    <a-select-option v-for="item in storeList" :key="item.id" :value="item.id">
      {{ item.name }}
      <template v-if="showCode"> ({{ item.code }})</template>
    </a-select-option>
  </a-select>
</template>

<script>
  import { defineComponent, ref, watch, onMounted } from 'vue';
  import { message, Spin } from 'ant-design-vue';
  import * as api from '@/api/base-data/store-center';

  export default defineComponent({
    name: 'MobileStoreCenterSelector',
    components: {
      Spin
    },
    props: {
      value: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: '请选择仓库'
      },
      allowClear: {
        type: Boolean,
        default: true
      },
      disabled: {
        type: Boolean,
        default: false
      },
      showCode: {
        type: Boolean,
        default: true
      },
      requestParams: {
        type: Object,
        default: () => {}
      },
      style: {
        type: Object,
        default: () => ({})
      }
    },
    emits: ['change'],
    setup(props, { emit }) {
      const storeList = ref([]);
      const loading = ref(false);
      const searchKey = ref('');
      const currentPage = ref(1);
      const hasMore = ref(true);
      const localValue = ref(props.value);

      const loadData = async (reset = false) => {
        if (loading.value || (!hasMore.value && !reset)) return;

        loading.value = true;
        try {
          const params = {
            code: reset ? '' : searchKey.value,
            name: reset ? '' : searchKey.value,
            available: true,
            pageNum: reset ? 1 : currentPage.value,
            pageSize: 99999, // 设置一个大数，避免分页
            ...props.requestParams
          };

          const response = await api.selector(params);
          
          const data = response.datas || [];

          if (reset) {
            storeList.value = data;
            currentPage.value = 1;
            hasMore.value = data.length < 99999;
          } else {
            // 去重处理
            const existingIds = new Set(storeList.value.map(item => item.id));
            const newItems = data.filter(item => !existingIds.has(item.id));
            storeList.value = [...storeList.value, ...newItems];
            hasMore.value = data.length === 99999;
          }
        } catch (error) {
          console.error('加载仓库数据失败:', error);
        } finally {
          loading.value = false;
        }
      };

      // 处理搜索
      const handleSearch = async (value) => {
        searchKey.value = value;
        await loadData(true);
      };

      // 处理选择变化
      const handleChange = (value) => {
        localValue.value = value;
        emit('change', value);
        emit('update:value', value);
      };

      // 处理下拉列表滚动加载更多
      const handlePopupScroll = () => {
        if (!loading.value && hasMore.value) {
          currentPage.value++;
          loadData();
        }
      };

      // 监听props.value变化，同步到localValue
      watch(() => props.value, (newValue) => {
        localValue.value = newValue;
        if (newValue && storeList.value.length > 0) {
          const exists = storeList.value.some(item => item.id === newValue);
          if (!exists) {
            // 如果当前值不在列表中，重新加载数据
            loadData(true);
          }
        }
      });

      // 组件挂载时加载数据
      onMounted(() => {
        loadData(true);
      });

      return {
        storeList,
        loading,
        localValue,
        handleSearch,
        handleChange,
        handlePopupScroll
      };

      // 修复TS警告：声明但未使用的变量
      const _unused = Spin;
    }
  });
</script>

<style lang="less">
  .ant-select {
    width: 100%;
    &-dropdown {
      max-height: 300px;
      overflow-y: auto;
    }
    &-option {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
</style>